package app.framework.exception;

import app.framework.common.Errors;
import app.framework.common.Status;
import app.framework.exception.ValidateException;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
public class GlobalExceptionHandler {
  @ExceptionHandler(value = Exception.class)
  @ResponseBody
  public JSONObject resolveException(Exception ex) {
    JSONObject errorObj = new JSONObject();
    errorObj.put("status", Status.ERROR.value());
    errorObj.put("error", ex.getMessage());
    if (ex instanceof ValidateException) {
      errorObj.put("code",((ValidateException) ex).getCode());
    } else {
      errorObj.put("code", Errors.OTHER.value());
    }
    return errorObj;
  }
}
